import React, { useState } from 'react';
import { IonCard, IonCardHeader, IonCardTitle, IonCardContent, IonItem, IonLabel, IonToggle, IonSelect, IonSelectOption, IonInput, IonButton, IonNote } from '@ionic/react';
import { useOllama } from '../../hooks/useOllama';
import { useTranslation } from 'react-i18next';

interface ServerConfig {
  debug: boolean;
  keepAlive: string;
  maxModelsPerGpu: number;
  maxQueueRequests: number;
  parallelRequests: number;
  scheduledSpread: boolean;
  flashAttention: boolean;
}

const ServerManagement: React.FC = () => {
  const { isServerRunning, startServer, stopServer } = useOllama();
  const { t } = useTranslation();
  const [config, setConfig] = useState<ServerConfig>({
    debug: false,
    keepAlive: '5m',
    maxModelsPerGpu: 1,
    maxQueueRequests: 10,
    parallelRequests: 1,
    scheduledSpread: false,
    flashAttention: false
  });

  const handleConfigChange = (key: keyof ServerConfig, value: any) => {
    setConfig(prev => ({ ...prev, [key]: value }));
  };

  const handleServerAction = async () => {
    try {
      if (isServerRunning) {
        await stopServer();
      } else {
        // Set environment variables based on config
        const env = {
          OLLAMA_DEBUG: config.debug ? '1' : '0',
          OLLAMA_MAX_LOADED_MODELS: config.maxModelsPerGpu.toString(),
          OLLAMA_MAX_QUEUE: config.maxQueueRequests.toString(),
          OLLAMA_NUM_PARALLEL: config.parallelRequests.toString(),
          OLLAMA_SCHED_SPREAD: config.scheduledSpread ? '1' : '0',
          OLLAMA_FLASH_ATTENTION: config.flashAttention ? '1' : '0'
        };
        await startServer();
      }
    } catch (error) {
      console.error('Failed to control server:', error);
    }
  };

  return (
    <IonCard>
      <IonCardHeader>
        <IonCardTitle>{t('server.title')}</IonCardTitle>
      </IonCardHeader>
      <IonCardContent>
        <div className="space-y-4">
          {/* Server Status and Control */}
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              <div className={`badge ${isServerRunning ? 'badge-success' : 'badge-error'}`}>
                {isServerRunning ? t('server.status.running') : t('server.status.stopped')}
              </div>
            </div>
            <IonButton
              color={isServerRunning ? 'danger' : 'success'}
              onClick={handleServerAction}
            >
              {isServerRunning ? t('server.actions.stop') : t('server.actions.start')}
            </IonButton>
          </div>

          {/* Server Configuration */}
          <div className="space-y-2">
            <IonItem>
              <IonLabel position="stacked">{t('server.config.debug')}</IonLabel>
              <IonToggle
                checked={config.debug}
                onIonChange={e => handleConfigChange('debug', e.detail.checked)}
              />
              <IonNote>{t('common.enabled')}</IonNote>
            </IonItem>

            <IonItem>
              <IonLabel position="stacked">{t('server.config.keepAlive')}</IonLabel>
              <IonSelect
                value={config.keepAlive}
                onIonChange={e => handleConfigChange('keepAlive', e.detail.value)}
              >
                <IonSelectOption value="5m">5 minutes</IonSelectOption>
                <IonSelectOption value="10m">10 minutes</IonSelectOption>
                <IonSelectOption value="30m">30 minutes</IonSelectOption>
                <IonSelectOption value="custom">Custom</IonSelectOption>
              </IonSelect>
            </IonItem>

            <IonItem>
              <IonLabel position="stacked">{t('server.config.maxModels')}</IonLabel>
              <IonInput
                type="number"
                value={config.maxModelsPerGpu}
                onIonChange={e => handleConfigChange('maxModelsPerGpu', parseInt(e.detail.value!, 10))}
                min={1}
              />
            </IonItem>

            <IonItem>
              <IonLabel position="stacked">{t('server.config.maxQueue')}</IonLabel>
              <IonInput
                type="number"
                value={config.maxQueueRequests}
                onIonChange={e => handleConfigChange('maxQueueRequests', parseInt(e.detail.value!, 10))}
                min={1}
              />
            </IonItem>

            <IonItem>
              <IonLabel position="stacked">{t('server.config.parallel')}</IonLabel>
              <IonInput
                type="number"
                value={config.parallelRequests}
                onIonChange={e => handleConfigChange('parallelRequests', parseInt(e.detail.value!, 10))}
                min={1}
              />
            </IonItem>

            <IonItem>
              <IonLabel position="stacked">{t('server.config.spread')}</IonLabel>
              <IonToggle
                checked={config.scheduledSpread}
                onIonChange={e => handleConfigChange('scheduledSpread', e.detail.checked)}
              />
              <IonNote>{t('common.enabled')}</IonNote>
            </IonItem>

            <IonItem>
              <IonLabel position="stacked">{t('server.config.flash')}</IonLabel>
              <IonToggle
                checked={config.flashAttention}
                onIonChange={e => handleConfigChange('flashAttention', e.detail.checked)}
              />
              <IonNote>{t('common.enabled')}</IonNote>
            </IonItem>
          </div>

          {/* Help/Info Section */}
          <div className="mt-4 p-4 bg-base-200 rounded-lg">
            <h3 className="text-lg font-semibold mb-2">{t('server.help.title')}</h3>
            <p className="text-sm">
              {t('server.help.description')}
            </p>
          </div>
        </div>
      </IonCardContent>
    </IonCard>
  );
};

export default ServerManagement; 